import EnergyDiagram, { HEIGHT_CONFIG } from '@/components/EnergyDiagram';
import React, { ReactNode, useEffect, useRef, useTransition } from 'react';
import { useState, useMemo, useCallback, memo } from 'react';
import {
  ActivityIndicator,
  Alert,
  RefreshControl,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  useWindowDimensions,
  View,
  ViewStyle,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import { Button, Icon, useAppTheme } from 'tsun-smart-ui';
import NoDeviceIcon from '@/assets/icon/nodevice.svg';
import NoStationIcon from '@/assets/icon/no-station.svg';
import { useNavigation } from '@react-navigation/native';
import LabelAndValue from '@/components/LabelAndValue';
import { useTranslation } from 'react-i18next';
import {
  stationApi,
  StationDTO,
  StationEnergyDiagramModel,
} from '@/services/api/stationApi';
import dayjs, { Dayjs } from 'dayjs';
import { colorScheme } from 'nativewind';
import { StackNavigationProp } from '@react-navigation/stack';
import Logo from '@/components/Logo';
import TrapezoidTab, { TrapezoidTabPanel } from '@/components/TrapezoidTab';
import SegmentRing from '@/components/SegmentRing';
import { PieChart, PieData } from '@see_you/react-native-charts-wrapper';

type StationSummaryProps = {
  station: StationDTO | null | undefined;
  showGradient?: boolean;
};

const StationSummary: React.FC<StationSummaryProps> = ({
  showGradient = true,
  ...props
}) => {
  const windowDimensions = useWindowDimensions();
  const navigation = useNavigation<StackNavigationProp<any>>();
  const { t } = useTranslation();
  const appTheme = useAppTheme();
  const [refreshing, loadingTransition] = useTransition();
  const [realTimeMode, setRealTimeMode] = useState(false);
  const timerRef = useRef<number>(null);
  const realTimeStartTimeRef = useRef<Dayjs>(null);

  const [stationEnergyDiagram, setStationEnergyDiagram] =
    useState<StationEnergyDiagramModel>();
  const [startingRealtimeMode, setStartingRealtimeMode] = useState(false);

  useEffect(() => {
    reloadData();

    return () => {
      checkIfShouldClearTimer();
    };
  }, [props.station]);

  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, []);

  const reloadData = useCallback(() => {
    loadingTransition(() => {
      let stationId = props.station?.id ?? 0;
      if (stationId) {
        stationApi.getEnergyDiagramInfo(stationId).then((res) => {
          setStationEnergyDiagram(res.data);
          checkIfShouldClearTimer();
        });
      }
    });
  }, [props.station]);

  const toggleRealtimeMode = useCallback(() => {
    if (realTimeMode && timerRef.current !== null) {
      clearInterval(timerRef.current);
      realTimeStartTimeRef.current = null;
    } else {
      setStartingRealtimeMode(true);
      stationApi
        .speedUpStationDataRate(props.station?.id ?? 0)
        .then((res) => {
          setRealTimeMode(true);
          setStartingRealtimeMode(false);
          realTimeStartTimeRef.current = dayjs();
          timerRef.current = setInterval(() => {
            if (checkIfShouldClearTimer()) {
              return;
            } else {
              reloadData();
            }
          }, 1000 * 10);
          reloadData();
        })
        .catch((reason) => {
          setStartingRealtimeMode(false);
        });
    }
  }, [realTimeMode, props.station]);

  const checkIfShouldClearTimer = useCallback((): boolean => {
    if (realTimeStartTimeRef.current) {
      const now = dayjs();
      const diff = now.diff(realTimeStartTimeRef.current, 'second');
      if (diff > 120) {
        setRealTimeMode(false);
        if (timerRef.current) {
          clearInterval(timerRef.current);
        }
        realTimeStartTimeRef.current = null;
        return true;
      }
    }
    return false;
  }, []);

  const renderContent = useCallback(() => {
    const hasInverter = Boolean(stationEnergyDiagram?.invertEnable);
    const hasDCU = false;
    let energyDiagram: React.ReactNode = null;
    if (stationEnergyDiagram) {
      energyDiagram = (
        <EnergyDiagram
          diagramData={stationEnergyDiagram}
          realtimeMode={realTimeMode}
          key={`${props.station?.id}-energy-diagram-${realTimeMode}`}
        />
      );
    } else {
      energyDiagram = (
        <ActivityIndicator
          color={appTheme.colors?.brand?.onPrimary}
          size={'small'}
          style={{ marginVertical: 24 }}
        />
      );
    }
    const haveAtLeastDevice = !!stationEnergyDiagram?.otherNode;
    let haveLastUpdateTime = Boolean(stationEnergyDiagram?.lastUpdateTime);
    let haveTodayData = Boolean(stationEnergyDiagram?.todayData);
    let restContent: ReactNode;
    if (haveAtLeastDevice) {
      restContent = (
        <>
          {haveLastUpdateTime && (
            <Text className="text-text3 text-center">
              {t('job.previousUpdate', { defaultValue: '上次更新' })}
              {'：'}
              {stationEnergyDiagram?.lastUpdateTime}
            </Text>
          )}
          <View className="flex-row gap-x-3 px-4">
            {hasDCU && (
              <BlockButton
                key={`${props.station?.id}-dcu`}
                iconName={'DCU'}
                nameKey="DCU工作模式"
                value="智能电表"
                onPress={() => navigation.navigate('DCUWorkingMode')}
                horizontal={!hasInverter}
              />
            )}
            {hasInverter && (
              <BlockButton
                key={`${props.station?.id}-inverter-control`}
                iconName={'control'}
                nameKey={'sys.app.micro.inverter.control'}
                value=""
                onPress={() => {
                  navigation.navigate('InverterControl', {
                    stationId: props.station?.id,
                  });
                }}
                horizontal={!hasDCU}
              />
            )}
          </View>

          {haveTodayData && (
            <SectionContainer
              key={`${props.station?.id}-today-data`}
              title={t('device.today_data', { defaultValue: '今日数据' })}
              icon={
                <Logo
                  name="currentTime"
                  backgroundColor={appTheme.colors?.brand?.primaryLight!}
                  color={appTheme.colors?.brand?.primary!}
                  round={false}
                />
              }
            >
              <View className="flex-wrap flex-row gap-y-3 py-4">
                {Object.entries(stationEnergyDiagram.todayData!).map(
                  ([key, value]) => (
                    <LabelAndValue
                      label={t(key)}
                      value={value}
                      style={styles.fieldItem}
                      key={key}
                    />
                  )
                )}
              </View>
            </SectionContainer>
          )}

          <TrapezoidTab className="mx-4 rounded-lg overflow-hidden">
            <TrapezoidTabPanel title="发电" name="fadian">
              <EletricUsage
                eletricData={[
                  {
                    title: '光伏直供',
                    value: 141.2,
                    percent: 0,
                  },
                  {
                    title: '电网购电',
                    value: 20,
                    percent: 0,
                  },
                  {
                    title: '储能放电',
                    value: 38,
                    percent: 0,
                  },
                ]}
              />
            </TrapezoidTabPanel>
            <TrapezoidTabPanel title="用电" name="fadian1">
              <EletricUsage
                eletricData={[
                  {
                    title: '光伏直供',
                    value: 141.2,
                    percent: 0,
                  },
                  {
                    title: '电网购电',
                    value: 20,
                    percent: 0,
                  },
                  {
                    title: '储能放电',
                    value: 38,
                    percent: 0,
                  },
                ]}
              />
            </TrapezoidTabPanel>
          </TrapezoidTab>

          <SectionContainer
            key={`${props.station?.id}-contribute`}
            title={t('sys.app.comm.contribute', { defaultValue: '社会贡献' })}
            icon={
              <Logo
                name="tree-green-board"
                backgroundColor={appTheme.colors?.success?.light!}
                color={appTheme.colors?.success?.primary!}
                round={false}
              />
            }
          >
            <View className="flex-row flex-wrap gap-y-3 py-4">
              <LabelAndValue
                label={t('sys.app.save.coal', { defaultValue: '节约标准煤' })}
                value={stationEnergyDiagram?.saveStaCoal}
                style={styles.fieldItem}
              />
              <LabelAndValue
                label={t('sys.app.co2.save', { defaultValue: 'CO2减排量' })}
                value={stationEnergyDiagram?.carDioRed}
                style={styles.fieldItem}
              />
              <LabelAndValue
                label={t('sys.app.tree.equal', { defaultValue: '等效植树量' })}
                value={stationEnergyDiagram?.equTreePlanQua}
                style={styles.fieldItem}
              />
            </View>
          </SectionContainer>
        </>
      );
    } else {
      restContent = (
        <View className="self-center items-center gap-3">
          <NoDeviceIcon width={48} height={48} className="self-center" />
          <Text className="self-center text-text2">
            {t('device.nodata', { defaultValue: '暂无设备' })}
          </Text>
          <Button
            icon={'add1'}
            size="medium"
            title={t('common.add.device', { defaultValue: '添加设备' })}
            className="self-center gap-2"
            onPress={() => {
              navigation.navigate('SelectDeviceCategory', {
                station: props.station,
              });
            }}
          />
        </View>
      );
    }
    const realTimeButtonTintColor = realTimeMode
      ? appTheme.colors?.brand?.primary
      : appTheme.colors?.neutral?.title;
    const isRealtimeModeAvailable =
      stationEnergyDiagram?.stationStatus === 'normal';
    return (
      <>
        <View className="gap-3">
          <View
            className=""
            key={'顶部流动图部分'}
            style={{ backgroundColor: 'transparent' }}
          >
            <View className="items-center flex-row gap-x-3" key={'天气和状态'}>
              {/* <View className="px-2 py-1 rounded-full" key={'天气'}>
                <Text className="text">25～29°C</Text>
              </View> */}
              {/* <Tag type="success">正常</Tag> */}
              <View className="flex-1" />
              {isRealtimeModeAvailable && (
                <TouchableOpacity
                  className="bg-text6 rounded-full shadow-sm px-2 py-1 items-center justify-center flex-row gap-x-1"
                  onPress={toggleRealtimeMode}
                  disabled={realTimeMode || startingRealtimeMode}
                >
                  {startingRealtimeMode ? (
                    <ActivityIndicator size={'small'} color={'#CCC'} />
                  ) : (
                    <Icon
                      name="real-time"
                      size={18}
                      color={realTimeButtonTintColor}
                    />
                  )}

                  <Text
                    style={{ color: realTimeButtonTintColor }}
                    className="leading-4 text-[12px] font-medium"
                  >
                    {startingRealtimeMode
                      ? t('sys.app.starting')
                      : t('sys.app.realtime', { defaultValue: '实时' })}
                  </Text>
                </TouchableOpacity>
              )}
            </View>

            <View className="items-center" key={'能量流动图以及更新时间'}>
              {energyDiagram}
            </View>
          </View>
          {restContent}
        </View>
      </>
    );
  }, [
    stationEnergyDiagram,
    colorScheme,
    t,
    appTheme,
    props.station,
    startingRealtimeMode,
    realTimeMode,
  ]);

  const renderNoStation = useCallback(() => {
    return (
      <>
        <NoStationIcon
          width={45}
          height={45}
          style={{
            marginTop: 180,
            alignSelf: 'center',
            marginBottom: 8,
          }}
        />
        <Text className="text-text4 self-center mb-4">
          {t('sys.app.no.station', { defaultValue: '暂无电站' })}
        </Text>
        <Button
          title={t('sys.app.station.create', { defaultValue: '创建电站' })}
          icon="add1"
          className="mb-11 self-center"
          size="medium"
          onPress={() => navigation.navigate('CreatePowerStation')}
        />
      </>
    );
  }, [t]);

  const haveNoStationOrEquipment = !props.station;
  const isDarkMode = appTheme.isDark === true;
  return (
    <>
      <View className="flex-1">
        {showGradient && !isDarkMode && (
          <LinearGradient
            colors={[
              '#DDF6EC',
              appTheme.colors?.background?.primary ?? 'transparent',
            ]}
            style={{
              position: 'absolute',
              left: 0,
              top: 0,
              right: 0,
              height: windowDimensions.height * 0.5,
            }}
          />
        )}
        <ScrollView
          className="flex-1 bg-transparent"
          contentContainerClassName="items-stretch gap-y-4 pb-10"
          refreshControl={
            <RefreshControl
              refreshing={refreshing}
              onRefresh={reloadData}
            />
          }
          showsVerticalScrollIndicator={false}
        >
          {haveNoStationOrEquipment ? renderNoStation() : renderContent()}
        </ScrollView>
      </View>
    </>
  );
};

export default memo(StationSummary);

type SectionContainerProps = {
  title: string;
  icon: React.ReactNode;
  style?: ViewStyle;
  children: ReactNode;
};

const SectionContainer: React.FC<SectionContainerProps> = React.memo(
  ({ title, icon, children, style }) => {
    return (
      <View className="items-center mx-4 rounded-lg bg-fill2 p-3" style={style}>
        <View className="flex-row items-center gap-x-1">
          <Text className="text-text3 text-[12px]">{icon}</Text>
          <Text className="text-text1 text-[15px] font-medium ml-2">
            {title}
          </Text>
          <View className="flex-grow" />
        </View>
        {children}
      </View>
    );
  }
);

type BlockButtonProps = {
  nameKey: string;
  value: string | undefined;
  iconName: string;
  onPress: () => void;
  horizontal: boolean;
};

const BlockButton: React.FC<BlockButtonProps> = React.memo((props) => {
  const appTheme = useAppTheme();
  const themeColor = appTheme.colors?.brand?.primary;
  const { t } = useTranslation();

  const renderHorizontal = useCallback(() => {
    let name: string | undefined = t(props.nameKey);
    let value = props.value;
    if (!props.value) {
      name = props.value;
      value = t(props.nameKey);
    }
    return (
      <TouchableOpacity
        className="rounded-lg bg-fill2 px-4 py-4 flex-row flex-1 items-center gap-3"
        onPress={props.onPress}
      >
        <Icon name={props.iconName} size={22} color={themeColor} />
        {Boolean(name) && (
          <Text className="text-text3 text-[15px] font-medium">{name}</Text>
        )}
        <Text className="text-text1 text-[15px] font-medium">{value}</Text>
        <View className="flex-1" />
        <Icon name="right" size={16} color="#CCC" />
      </TouchableOpacity>
    );
  }, [t]);

  if (props.horizontal) {
    return renderHorizontal();
  }
  return (
    <TouchableOpacity
      className="rounded-lg bg-text6 px-4 py-3 flex-1 gap-1"
      onPress={props.onPress}
    >
      <Icon name={props.iconName} size={22} color={themeColor} />
      <View className="flex-row justify-between items-center">
        <Text className="text-text1 text-[14px] font-medium">{props.name}</Text>
        <Icon name="right" size={16} color="#CCC" />
      </View>
    </TouchableOpacity>
  );
});

type EletricData = {
  title: string;
  value: number;
  percent: number;
};

type EletricUsageProps = {
  eletricData: EletricData[];
};

const EletricUsage = React.memo((props: EletricUsageProps) => {
  const data: EletricData[] = useMemo(() => {
    let total = 0;
    for (const element of props.eletricData) {
      total += element.value;
    }
    return props.eletricData.map((v) => ({
      ...v,
      percent: (v.value / total) * 100,
    }));
  }, [props.eletricData]);

  const dataPie: PieData = {
    dataSets: [
      {
        values: data.map((segment) => ({
          value: segment.percent,
          label: segment.title,
        })),
        config: {
          // colors: [
          //   '#FF6B6B',
          //   '#4ECDC4',
          //   '#45B7D1',
          //   '#96CEB4',
          //   '#FECA57',
          //   '#FF9FF3',
          // ],
          sliceSpace: 4, // 段间间隔
          drawValues: false,
        },
        label: '111',
      },
    ],
  };

  return (
    <View className="flex-row justify-between items-center">
      <View className="items-start gap-3">
        {data.map((v) => {
          return (
            <View className="items-start gap-1" key={v.title}>
              <Text className="text-[12px] text-text3">{v.title}</Text>
              <Text className="text-[18px] font-medium text-text1">
                {v.value}
                {'  '}
                <Text className="text-[14px]">
                  {(v.percent ?? 0).toFixed(2)}%
                </Text>
              </Text>
            </View>
          );
        })}
      </View>
      <SegmentRing
        data={data}
        gapDegrees={12}
        size={150} // 必须是正数
        padding={10} // 可选
      />
    </View>
  );
});

const styles = StyleSheet.create({
  fieldItem: { width: '48%', height: 55, justifyContent: 'space-between' },
});
